package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.query.JsonResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/permission")
public class PermissionController {
    @Autowired
    private IPermissionService permissionService;

    // 查询所有请求信息
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo){
        PageInfo<Permission> pageResult = permissionService.query(qo);
        model.addAttribute("result",pageResult);
        return "permission/list";
    }

    // 删除信息
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){
        try {
            if (id != null) {
                permissionService.delete(id);
                return new JsonResult(true,"删除成功");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(true,"删除失败");
    }


    // 跳转到添加新的页面
    @RequestMapping("/input")
    public String input(Model model,Long id){
        // 如果 id 不为空,携带该 id 对应的数据过 input 视图
        if (id != null) {
            model.addAttribute("permission",permissionService.get(id));
        }
        // 跳转到 input 视图
        return "permission/input";
    }

    // 添加 或 修改 信息
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Permission permission){
        if (permission.getId() != null) {
            // 如果 id 不为空,调用 修改方法
            permissionService.update(permission);
        }else {
            // 如果 id 为空,调用保存方法
            permissionService.save(permission);
        }
        return "redirect:/permission/list.do";
    }

    @RequestMapping("/reload")
    @ResponseBody
    public JsonResult getReload() {
        try {
            // 如果权限加载成功,返回数据
            permissionService.reload();
            return new JsonResult(true,"加载成功");

        } catch (Exception e) {
            e.printStackTrace();
            // 如果权限加载成功,返回错误信息
        }
        return new JsonResult(false,"加载失败");

    }



}
